package br.com.android.financas.activities;

import java.sql.SQLException;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.PeriodType;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import br.com.android.financas.R;
import br.com.android.financas.adapter.DataAdapter;
import br.com.android.financas.fragments.DatePickerFragment;
import br.com.android.financas.helper.HomeHelper;
import br.com.android.financas.model.Receita;
import br.com.android.financas.repositorio.RepositorioReceita;
import br.com.android.financas.repositorio.impl.RepositorioReceitaImpl;
import br.com.android.financas.watcher.CurrencyWatcher;

public class HomeReceita extends HomeHelper<Receita> {

	private static final String CLICK_RECEITA_ID = "receitaId";

	private EditText campoValor;
	private Spinner campoData;
	private Spinner campoAte;
	private EditText campoDescricao;
	private RepositorioReceita repositorioReceita;
	private DataAdapter adapterAte;
	private Activity activity;
	private CheckBox permanente;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.receita_screen);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		try {
			repositorioReceita=new RepositorioReceitaImpl(this);

			Intent intent = getIntent();
			campoData= (Spinner) findViewById(R.receita.data);
			campoAte= (Spinner) findViewById(R.receita.ate);
			permanente=(CheckBox) findViewById(R.receita.permanente);
			campoValor=(EditText) findViewById(R.receita.valor);
			campoDescricao=(EditText) findViewById(R.receita.descricao);
			String data=(new DateTime()).toString("dd/MM/yyyy");
			if (intent.getExtras() != null
					&& intent.getExtras().get("id") != null) {

				Integer id = (Integer) intent.getExtras().get("id");
				setId(id);

				campoValor.setText(NumberFormat.getCurrencyInstance().format(getInstance().getValor()));
				data= (new DateTime(getInstance().getData().getTime())).toString("dd/MM/yyyy");
				campoDescricao.setText(getInstance().getDescricao());

				if(getInstance().isPai() || getInstance().getPai()!=null){
					TextView label=(TextView) findViewById(R.receita.label_ate);
					campoAte.setVisibility(View.VISIBLE);
					label.setVisibility(View.VISIBLE);
					permanente.setChecked(true);

					DateTime at=new DateTime(getInstance().getUltimoFilho().getData().getTime());

					List<String> datasAte=new ArrayList<String>();
					datasAte.add(at.toString("dd/MM/yyyy"));
					adapterAte=new DataAdapter(this, android.R.layout.simple_spinner_item, datasAte);
					adapterAte.setMinimo(at);
					adapterAte.setDataSelecionada(at);
					campoAte.setAdapter(adapterAte);
				}

			}

			List<String> datas=new ArrayList<String>();

			datas.add(data);

			DataAdapter dataAdapter= new DataAdapter(this, android.R.layout.simple_spinner_item, datas);
			dataAdapter.setDataSelecionada(new DateTime(getInstance().getData().getTime()));
			campoData.setAdapter(dataAdapter);
			campoValor.addTextChangedListener(new CurrencyWatcher(campoValor));


			activity=this;
			permanente.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean check) {
					TextView label=(TextView) findViewById(R.receita.label_ate);
					if(check){
						campoAte.setVisibility(View.VISIBLE);
						label.setVisibility(View.VISIBLE);
						try {
							DateTime at;
							at = new DateTime(new SimpleDateFormat("dd/MM/yyyy").parse((String) campoData.getSelectedItem()).getTime()).plusMonths(1);
							List<String> datasAte=new ArrayList<String>();
							datasAte.add(at.toString("dd/MM/yyyy"));

							adapterAte=new DataAdapter(activity, android.R.layout.simple_spinner_item, datasAte);
							adapterAte.setMinimo(at);
							adapterAte.setDataSelecionada(at);

							campoAte.setAdapter(adapterAte);

						} catch (ParseException e) {
							e.printStackTrace();
						}
					}else{
						campoAte.setVisibility(View.INVISIBLE);
						label.setVisibility(View.INVISIBLE);
					}

				}
			});

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void showDatePickerDialog(final View v) {
		OnDateSetListener ondate = new OnDateSetListener() {
			  @Override
			  public void onDateSet(DatePicker view, int year, int monthOfYear,
			    int dayOfMonth) {
				  Date data=new Date(view.getCalendarView().getDate());
				 ((EditText) v).setText(new SimpleDateFormat("dd/MM/yyyy").format(data));


			  }
			 };

		DatePickerFragment newFragment = new DatePickerFragment();
	    newFragment.setCallBack(ondate);
	    newFragment.show(getFragmentManager(), "datePicker");


	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.home_receita, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;

		switch (item.getItemId()) {
		case android.R.id.home:
			// app icon in action bar clicked; go home
			getIntent().putExtra("changed", false);
			setResult(RESULT_CANCELED, getIntent());
			finish();
			return true;
		case R.id.menu_save:

			try{

				if(!isValid()){
					Toast.makeText(this, R.string.required_fields, Toast.LENGTH_LONG).show();
					return false;
				}

				if (getInstance().getId() == null) {
					salva();

				} else {
					atualizar();
				}
			}catch(SQLException e){
				e.printStackTrace();
			}



			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void salva() throws SQLException {

		try {
			if(permanente.isChecked()){
				Date at = new SimpleDateFormat("dd/MM/yyyy").parse(campoAte.getSelectedItem().toString());
				DateTime ini = new DateTime(getInstance().getData().getTime());
				DateTime fim = new DateTime(at.getTime());

				Period p = new Period(ini, fim, PeriodType.months().withDaysRemoved());
				int qtd = p.getMonths();
				qtd=qtd==0? (ini.isEqual(fim)?1:0):qtd+1;
				if (qtd > 0 ) {


					repositorioReceita.inserir(getInstance());

					double valor = getInstance().getValor();
					String descricao=getInstance().getDescricao();
					for (int i = 1; i < qtd; i++) {
						Receita d = new Receita();
						d.setDescricao(descricao);
						d.setValor(valor);
						d.setData(ini.plusMonths(i).toDate());
						d.setPai(getInstance());

						repositorioReceita.inserir(d);
					}
				}
			}else{
				repositorioReceita.inserir(getInstance());
			}

			getIntent().putExtra("changed", true);
			setResult(RESULT_OK, getIntent());
			finish();

		} catch (ParseException e) {
		}

	}


	public static void callMe(Context c, Integer id) {
		Intent intent = new Intent(c, HomeReceita.class);
		intent.putExtra(CLICK_RECEITA_ID, id);
		c.startActivity(intent);
	}

	private void atualizar(){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);


		LayoutInflater factory = LayoutInflater.from(this);
	    View layout = factory.inflate(R.layout.apagar_despesa, null);
		final CheckBox todas = (CheckBox) layout.findViewById(R.apagar.todasGrupo);
		final CheckBox frente = (CheckBox) layout.findViewById(R.apagar.paraFrente);


		if( ( getInstance().isPai() || getInstance().getPai()!=null)){

			todas.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton arg0, boolean check) {
					if(check){
						frente.setVisibility(View.INVISIBLE);
					}else
						frente.setVisibility(View.VISIBLE);
				}
			});

			builder.setView(layout);
			builder.setTitle(R.string.atualizar_movimentacoes);
		}else{
			builder.setTitle(R.string.atualizar_movimentacao);
			builder.setMessage(R.string.confirmar_atualizacao);
		}


		builder.setCancelable(false);
		builder.setPositiveButton(R.string.sim,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						try {
							if (getInstance() != null){
								DateTime dataUltima=null;
								if(todas.isChecked()){
									dataUltima=new DateTime(getInstance().getUltimoFilho().getData().getTime());
									repositorioReceita.atualizarGrupo(getInstance());
								}else if(frente.isChecked())
								{
									dataUltima=new DateTime(getInstance().getUltimoFilho().getData().getTime());
									repositorioReceita.atualizarGrupo(getInstance(),getInstance().getData());
								}else{
									repositorioReceita.atualizar(getInstance());
								}

								if(dataUltima!=null){
									try {
										DateTime at = new DateTime(new SimpleDateFormat("dd/MM/yyyy").parse(campoAte.getSelectedItem().toString()).getTime());

										if(dataUltima.isBefore(at)){
											Period p = new Period(dataUltima, at, PeriodType.months().withDaysRemoved());
											int qtd = p.getMonths();

											int a= getInstance().isPai()?getInstance().getFilhos().size():getInstance().getPai().getFilhos().size();
											qtd+=a;
											if (qtd > 0 ) {

												String descricao=getInstance().getDescricao();
												//descricao=descricao.replaceAll("\\d+\\/\\d+", "");
												//descricao.trim();
												Receita pai=getInstance().isPai()?getInstance():getInstance().getPai();
												double valor = getInstance().getValor();
												DateTime ini=new DateTime(getInstance().getUltimoFilho().getData().getTime());
												int b=1;
												for (int i = a; i < qtd; i++) {
													Receita d = new Receita();
													d.setDescricao(descricao);
													d.setValor(valor);
													d.setData(ini.plusMonths(b).toDate());
													d.setPai(pai);
													b++;
													repositorioReceita.inserir(d);
												}

											}

										}

									} catch (ParseException e) {
										// TODO Auto-generated catch block
										e.printStackTrace();
									}
								}
							}

							Toast.makeText(activity,"Atualizados com sucesso!", Toast.LENGTH_LONG).show();
							getIntent().putExtra("changed", true);
							setResult(RESULT_OK, getIntent());
							finish();
						} catch (SQLException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

					}
				});
		builder.setNegativeButton(R.string.nao,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();


	}
}
